Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Stata does not recognize foreach loop: "} is not a valid command name r(199);"

    Dear community,

    I have a problem with the following loop:

    Code:
    foreach var in variable1 variable2 {
        forval x=1(1)5 {
            gen `var'_t`x' = .
            forval j=1(1)`x' {
                bysort id (year): replace `var'_t`x' = `var'[_n-`j'] if year[_n]-year[_n-`j']==`x'
            }
        }
    }
    When I run my entire do-file, it stops at these loops and gives the following error:

    } is not a valid command name
    r(199);

    Moreover, it does not create variables variable1_t1, ..., variable1_t5 and variable2_t1, ..., variable2_t5. Instead, it just creates variables t1, t2, t3, t4 and t5. Clearly, stata does not seem to recognize the outer foreach loop. Or rather, it does not seem to recognize the variables variable1 and variable2. Strangely, if I only run the above code section after I got the error from running my entire do-file, the error does not occur and the loops runs smoothly and produce the desired result. Why does it not work on first try when I run the entire do-file?

    Finally, later on I have a similar loop that runs through without any problems:

    Code:
    foreach var in variable1 variable2  {
        forval i=1(1)5 {
            bysort id (year): gen `var't`i' = `var'[_n-`i'] if year[_n]-year[_n-`i']==`i'
        }
    }
    Thanks for your help!

    P.S.: I am using stata 17 on macOS Sonoma 14.2

  • #2
    I made up a small dataset to test your code in the absence of a data example. This ran for me:

    Code:
    clear
    set obs 10 
    gen id = 1 
    gen year = _n 
    gen variable1 = 42
    gen variable2 = 666 
    
    foreach var in variable1 variable2 {
        forval x=1(1)5 {
            gen `var'_t`x' = .
            forval j=1(1)`x' {
                bysort id (year): replace `var'_t`x' = `var'[_n-`j'] if year[_n]-year[_n-`j']==`x'
            }
        }
    }
    You may have awkward invisible characters in your code. Push your code as a file through hexdump to check.

    Comment


    • #3
      Thanks for the quick reply! That solved the issue

      Comment

      Working...
      X